package com.vortex.cloud.sample.utils;

import com.vortex.cloud.sample.annotation.FieldLin;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.text.DecimalFormat;

/**
 * @author 王林
 * @version 1.0
 * @date 2021-10-22 周五
 * @time 16:15
 * @description 自定义注解验证
 */
public class MyAnnotationUtils {

    public static void validateParameter(Object object) throws Exception {
        Class clazz = object.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            Annotation[] annotations1 = field.getAnnotations();
            for (Annotation annotation : annotations1) {
                if (annotation instanceof FieldLin) {
                    //获取有该注解上字段的值
                    Double fieldData = (Double) field.get(object);
                    if (fieldData > 100.00) {
                        throw new RuntimeException(field.getName() + "长度超出范围，请设置100以为的值");
                    }
                    //统一设置为 保留2位小数
                    DecimalFormat format2 = new DecimalFormat("0.00 ");
                    fieldData = Double.parseDouble(format2.format(fieldData));
//                    System.out.println(fieldData);
//                    System.out.println(field.getName() + "有" + annotation.getClass() + "注解");
                }
            }
        }
    }
}
